﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace YiLong.Framework.Serialization
{
    public class SerializeUtil
    {
        public static T DeepClone<T>(T obj) where T : class,new()
        {
            string xml = SerializeToXml<T>(obj);

            return DeserializeXml<T>(xml);
        }

        public static String SerializeToXml<T>(T obj) where T : class,new()
        {
            XmlSerializer ser = new XmlSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            try
            {
                ser.Serialize(ms, obj);

                String str = Encoding.UTF8.GetString(ms.ToArray());
                ms.Dispose();
                return str;
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

        public static T DeserializeXml<T>(string xml) where T:class,new()
        {
            XmlSerializer ser = new XmlSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            byte[] bytes = Encoding.UTF8.GetBytes(xml);
            ms.Write(bytes,0,bytes.Length);
            ms.Position = 0;
            return ser.Deserialize(ms) as T;
        }

        public static T LoadFromXml<T>(string fileName) where T : class,new()
        {
            FileStream fs = null;

            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(fs);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Dispose();
                }
            }
        }

        public static void SaveToXml<T>(T data, string fileName) where T : class, new()
        {
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(fs, data);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Dispose();
                }
            }
        }
    }
}
